//
//  ZXZNetworkManager.swift
//  up_learnWB
//
//  Created by Mac on 16/10/23.
//  Copyright © 2016年 www.ZXZ123.com. All rights reserved.
//

import UIKit


enum ZXZNetworkMethod {
    case GET
    case  POST
}
private let access_token:String? = "2.00obbz_G08maOXa466719b66XK9pHE"

class ZXZNetworkManager: AFHTTPSessionManager {



    /// j静态去 常量 闭包
    // 第一次访问的时候, 执行闭包. 并且将结果保存在shareTools
    static var shareTools = ZXZNetworkManager()


    /// 将token包起来  不让在外界接触掉
    ///
    /// - parameter method:     什么方法
    /// - parameter URLString:  请求的地址
    /// - parameter parameters: 参数
    /// - parameter compose:    回调
    func takeToken(method:ZXZNetworkMethod = .GET, URLString: String, parameters: [String:AnyObject]?, compose: @escaping (_  callData:Any?,  _ isSuccess:Bool) ->()) -> (){

        guard let token = access_token else {

            // token没有  我们应该通知  告诉用户重新登录
            compose(nil, false)
            print("没有token 请登录")
            return
        }

        var  para = parameters

        if para == nil {
            para = [String:AnyObject]()
        }

        para!["access_token"] = access_token as AnyObject?


        
        requestNetWork(method: method, URLString: URLString, parameters: para, compose: compose)
    }

    /// 基本的网络请求的函数
    ///
    /// - parameter method:     什么方法
    /// - parameter URLString:  请求的地址
    /// - parameter parameters: 参数
    /// - parameter compose:    回调
    private func requestNetWork(method:ZXZNetworkMethod = .GET, URLString: String, parameters: [String:AnyObject]?, compose: @escaping (_  callData:Any?,  _ isSuccess:Bool) ->() ) -> () {

        let success = { (task:URLSessionDataTask, data:Any?) -> () in

            compose(data, true)

        }

        let error  = { (task:URLSessionDataTask?, error:Error) -> () in

            //FIXME 判断 403 处理用户token过期 // token没有  我们应该通知  告诉用户重新登录
            if (task?.response as? HTTPURLResponse)?.statusCode == 400 {
                print("现在我们的token值过期了")
            }
            print("我们的请求是错误的 \(error)")
            compose(nil, false)
        }


        switch method {
        case ZXZNetworkMethod.GET:
            get(URLString, parameters: parameters, progress: nil, success: success, failure: error)
        case ZXZNetworkMethod.POST:
            post(URLString, parameters: parameters, progress: nil, success: success, failure: error)
            
        default:
            return
            
        }
        
        
    }
    
}













